package com.ip.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class ImageUtils {

    /**
     * 缩放图片方法
     * @param srcImageFile 要缩放的图片路径
     * @param targerImageFile 缩放后的图片路径
     * @param height 目标高度像素
     * @param width  目标宽度像素
     * @param isPadding     是否补白
     */
    public final static void scale(File srcImageFile, String targerImageFile, int width, int height, String fileExtName, boolean isPadding) throws IOException{
        try {
            BufferedImage srcImage = ImageIO.read(srcImageFile);
            BufferedImage targerImage = zoomImage(srcImage, width, height, isPadding);
            System.out.println(targerImageFile);
            File outFile=new File(targerImageFile);
            if(!outFile.exists() && !outFile.isDirectory()) {
                outFile.mkdir();
                ImageIO.write(targerImage, fileExtName, outFile);
            } else  {
                ImageIO.write(targerImage, fileExtName, outFile);
            }

        } catch (IOException e) {
            e.printStackTrace();
            log.error("图片切图错误", e);
        }
    }

    /**
     * 缩放图片方法
     * @param srcImageFile 要缩放的图片路径
     * @param height 目标高度像素
     * @param width  目标宽度像素
     * @param isPadding     是否补白
     */
    public final static byte[] scale(File srcImageFile, int width, int height, String fileExtName, boolean isPadding) throws IOException{
        return scale(toImage(srcImageFile), width, height, fileExtName, isPadding);
    }

    /**
     * 缩放图片方法
     * @param srcImageFile 要缩放的图片路径
     * @param height 目标高度像素
     * @param width  目标宽度像素
     * @param isPadding     是否补白
     */
    public final static byte[] scale(byte[] srcImageFile, int width, int height, String fileExtName, boolean isPadding) throws IOException {
        return scale(toImage(srcImageFile), width, height, fileExtName, isPadding);
    }

    /**
     * 缩放图片方法
     * @param srcImage 要缩放的图片BufferedImage
     * @param height 目标高度像素
     * @param width  目标宽度像素
     * @param isPadding     是否补白
     */
    public final static byte[] scale(BufferedImage srcImage, int width, int height, String fileExtName, boolean isPadding) throws IOException {
        byte[] bytes = null;
        BufferedImage targerImage = zoomImage(srcImage, width, height, isPadding);
        if(targerImage != null){
            bytes = FileUtils.image2byte(targerImage, fileExtName);
        }
        return bytes;
    }

    public static BufferedImage toImage(File file) throws IOException {
        return ImageIO.read(file);
    }
    public static BufferedImage toImage(String fileUrl) throws IOException {
        File file = new File(fileUrl);
        return toImage(file);
    }

    public static BufferedImage toImage(InputStream inputStream) throws IOException {
        return ImageIO.read(inputStream);
    }

    public static BufferedImage toImage(byte[] bytes) throws IOException {
        return ImageIO.read(FileUtils.byte2InputStream(bytes));
    }

    public static BufferedImage zoomImage(BufferedImage srcImage, int width, int height, boolean isPadding){
        BufferedImage targerImage = null;
        double ratio = 0.0; // 缩放比例
        //bi.SCALE_SMOOTH  选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
//        Image itemp = srcImage.getScaledInstance(width, height, srcImage.SCALE_SMOOTH);
        // 计算比例
        int srcWidth = srcImage.getWidth();
        int srcHeight = srcImage.getHeight();
        if ((srcWidth > width) || (srcHeight > height)) {
            double ratioWhidth = (new Integer(width)).doubleValue() / srcWidth;
            double ratioHeight = (new Integer(height)).doubleValue() / srcHeight;
            if(ratioWhidth > ratioHeight){
                ratio= ratioHeight;
            }else{
                ratio= ratioWhidth;
            }

            int zoomWidth = (int)(ratio * srcWidth);
            int zoomHeight = (int)(ratio * srcHeight);
            targerImage = new BufferedImage(zoomWidth, zoomHeight, BufferedImage.TYPE_INT_RGB);
            targerImage.getGraphics().drawImage(srcImage.getScaledInstance(zoomWidth, zoomHeight,  Image.SCALE_SMOOTH), 0, 0,  null);

        } else {
            //图片尺寸太小
            return srcImage;
        }
        //补白
        if (isPadding) {
            //构造一个类型为预定义图像类型之一的 BufferedImage。
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //创建一个 Graphics2D，可以将它绘制到此 BufferedImage 中。
            Graphics2D g = image.createGraphics();
            //控制颜色
            g.setColor(Color.white);
            // 使用 Graphics2D 上下文的设置，填充 Shape 的内部区域
            g.fillRect(0, 0, width, height);
            if (width == targerImage.getWidth()) {
                g.drawImage(targerImage, 0, (height - targerImage.getHeight()) / 2,
                        targerImage.getWidth(), targerImage.getHeight(),
                        Color.white, null);
            } else {
                g.drawImage(targerImage, (width - targerImage.getWidth()) / 2, 0,
                        targerImage.getWidth(null), targerImage.getHeight(),
                        Color.white, null);
            }
            g.dispose();
            targerImage = image;
        }
        return targerImage;
    }



    public static boolean makeImages(BufferedImage bi, String path, int height, int width, String fileExtName) throws IOException {

        // 缩放
        double ratioHeight = 0.0;
        double ratioWidth = 0.0;
        ratioHeight = ((double) height) / bi.getHeight();
        ratioWidth = ((double) width) / bi.getWidth();

        AffineTransformOp op = new AffineTransformOp(AffineTransform .getScaleInstance(ratioWidth, ratioWidth), null);
        BufferedImage targerImage = op.filter(bi, null);

        // Image image = bi.getScaledInstance(width,
        // height, BufferedImage.SCALE_SMOOTH);

        File outFile=new File(path);
        if(!outFile.exists() && !outFile.isDirectory()) {
            outFile.mkdir();
            ImageIO.write(targerImage, fileExtName, outFile);
        } else  {
            ImageIO.write(targerImage, fileExtName, outFile);
        }
        // image = null;


//		if (result) {
//			// 去色
//			BufferedImage grayImage = new BufferedImage(
//					defaultImage.getWidth(), defaultImage.getHeight(),
//					defaultImage.getType());
//			grayImage.getGraphics().drawImage(
//					GrayFilter.createDisabledImage(defaultImage), 0, 0, null);
//			ImageIO.write(grayImage, "gif", getFile(path, userId, height, 50));
//
//			// 闪烁
//			grayImage.getGraphics().setColor(Color.WHITE);
//			grayImage.getGraphics().fillRect(0, 0, width, height);
//			AnimatedGifEncoder e = new AnimatedGifEncoder();
//			e.setRepeat(0);
//			e.start(getFileName(path, userId, height, 60));
//			e.setDelay(400);
//			e.addFrame(defaultImage);
//			e.setDelay(300);
//			e.addFrame(grayImage);
//			e.finish();
//
//			// 叠加图片
//			complexImage(path, userId, height, defaultImage, 20);
//			complexImage(path, userId, height, defaultImage, 30);
//			complexImage(path, userId, height, defaultImage, 40);
////			complexImage(path, userId, height, defaultImage, 100);
//		}

        return true;
    }


    public static void main(String[] args) {
        String srcUrl = "/Users/mxli/Desktop/test.png";
        String targerUrl = "/Users/mxli/Desktop/test.png_targer.png";
        try {
            File srcFile = new File(srcUrl);
            BufferedImage inputBufImage = ImageIO.read(srcFile);
            byte[] bytes = scale(srcFile,500,500, "png", true);
            BufferedImage targerImage = toImage(bytes);
            File outFile=new File(targerUrl);
            if(!outFile.exists() && !outFile.isDirectory()) {
                outFile.mkdir();
                ImageIO.write(targerImage, "png", outFile);
            } else  {
                ImageIO.write(targerImage, "png", outFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
